package com.lance.answer.question_answer.tmp;

import com.google.common.base.Strings;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
public class WatchVideo1010tmp2 {

    //http://www.nmg.gov.cn/mas/openapi/pages.do?method=exPlay&appKey=gov&id=5716&autoPlay=false
    //https://vod.300hu.com/4c1f7a6atransbjngwcloud1oss/5d82e52a382171174942019585/v.f30.mp4
    //http://vfx.mtime.cn/Video/2019/02/04/mp4/190204084208765161.mp4
    //https://jvod.300hu.com/vod/product/a7d50669-f57b-4da9-8cf8-43d04372cab0/0411e189a55b41cfada876041fa7fdd7.mp4?source=2&h265=h265/18799/d7d0ab77577f4ea0bcf5bc794316045a.mp4
    public static  final String JS = "var video = document.getElementsByTagName(\"video\");if(video.length>0){ video[0].src = \"https://jvod.300hu.com/vod/product/a7d50669-f57b-4da9-8cf8-43d04372cab0/0411e189a55b41cfada876041fa7fdd7.mp4?source=2&h265=h265/18799/d7d0ab77577f4ea0bcf5bc794316045a.mp4\";}";

    public static void main(String[] args) throws Exception {
        //课程名
        String subjectName = "形势与政策";
        //  String subjectName = "马克思主义基本原理概论";
        //专业名
        //   String majorName = "工商企业管理";
        // String majorName = "法律事务";
        //   String majorName = "小学教育";
        //     String majorName = "工程造价";  //FIXME 工程造价是马克思主义！！！！！！！！
        //  String majorName = "计算机信息管理";
   //     String majorName = "all1";
      //  String majorName = "行政管理专科2103"; //DONE
    //    String majorName = "建设工程管理专科2013秋"; // DONE
        String majorName = "other";
        // FIXME 会计学 马克思主义基本原理概论
        // all: 人力资源管理 机电一体化 水利水电工程管理 汉语言文学 计算机网络技术 金融管理
        // all2: 工程造价 会计学
        //并发度
        int sync = 10;
        //是否开启休眠-兼容服务器停服
        boolean open = false;

        run(subjectName.trim(),majorName.trim(),sync,open);
    }

    public static void run (String subjectName,String majorName,int sync,boolean open) throws Exception {
        //初始化日志
        Constant.initLog();
        //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
        InputStream inputStream3 = Thread.currentThread().getContextClassLoader().getResourceAsStream( subjectName + "/" + subjectName +"-video.section");
        List<String> paths = IOUtils.readLines(inputStream3);

        InputStream inputStream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream( subjectName + "/" + "users/" + majorName  + ".user");
        List<String> users = IOUtils.readLines(inputStream2,"utf-8");

        log.info("本次刷视频 课程名称：{},专业名称：{}",subjectName,majorName);
        log.info("本次加载用户：{} 人",users.size());

        List<List<String>> group = new ArrayList<>();
        int size = users.size();
        int step = size / sync;
        if (step == 0) {
            group.add(users);
        } else {
            for (int i = 0; i < sync; i++) {
                List<String> list2 = users.subList(step * i, (i + 1) * step);
                group.add(list2);
            }
            group.add(users.subList(step * sync, users.size()));
        }

        log.info("本次程序将加载 {} 个线程同时运行",group.size());
        for (List<String> batchUser : group) {
            Constant.THREAD_POOL_BATCH.execute(() -> {
                try {
                    int i = 1;
                    log.info("线程：{} 将执行 {} 个用户视频观看任务",Thread.currentThread().getName(),batchUser.size());
                    for (String user : batchUser) {
                        String[] strs = user.split(",");
                        String userCode = strs[0];
                        String pwd;
                        if(strs[1].length()==8){
                            pwd = strs[1];
                        }else {
                            pwd = strs[1].substring(6, 14);
                            pwd = "Ouchn"+pwd;
                        }

                        long start = System.currentTimeMillis();
                        log.info("线程：{} 开始执行第：{} 个用户视频观看任务，用户名：{}",Thread.currentThread().getName(),i,userCode);
                     //   run(paths,subjectName,"d:\\ynouAutoStudy\\chromedriver.exe",userCode,pwd,open);
                        run(paths,subjectName,null,userCode,pwd,open);

                        long end = System.currentTimeMillis();
                        log.info("线程：{} 第：{} 个用户视频观看任务结束,耗时：{} min,用户名：{}",Thread.currentThread().getName(),i, (end - start) / 1000 / 60,userCode);
                        log.info("线程：{} 当前用户进度：{} / {}",Thread.currentThread().getName(),i,batchUser.size());
                        i++;
                    }
                    log.info("线程：{} 任务执行完毕",Thread.currentThread().getName());


                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

        }

    }

    public static void run(List<String> urlTasks,String subjectName,String driverPath,String userName,String password,boolean open) throws Exception {
        ChromeDriver driver = Util.getDriver(driverPath);
        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        driver.get(url);
        Thread.sleep(6000);
        Util.login(driver, userName, password);
        //Util.switchToLast(driver);
        Thread.sleep(6000);
        // 形考作业的链接 管理学
        //List<String> urlTasks = Util.getCourseTaskUrl(driver, CourseTypeEnum.BasicManagement.name);
        //List<String> urlTasks = Util.getCourseTaskUrl(subjectCode);
        for (WebElement we : driver.findElements(By.className("media-body"))) {
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();

            if (!mediaTitle.contains(subjectName)) {
                continue;
            }
            //点击进入学习的按钮
            WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
            studyButton.click();
            //Util.switchToLast(driver);

         //   String js = "window.open(\"http://xinjiang.ouchn.cn/course/view.php?id=2660&sectionid=118818&mid=343895\");";
        //    ((JavascriptExecutor) driver).executeScript(js);

            Thread.sleep(6000);
        }

        // 通过判断是否可以点击第五次形考 来判断视频是否刷完了
      //  Util.switchToFirst(driver);
        driver.get("http://xinjiang.ouchn.cn/mod/quiz/view.php?id=343896");
        Thread.sleep(5000);
        boolean hasGoOn = true;
        for (WebElement we : driver.findElements(By.cssSelector("button[class='btn btn-secondary']"))) {
            if ("现在试答".equals(we.getText().trim())|| "继续上次试答".equals(we.getText().trim())|| "点击进入".equals(we.getText().trim())) {
                hasGoOn = false;
            }
        }
        if(!hasGoOn){
            System.err.println("完成！");
            driver.close();
            driver.quit();
            return;
        }

       // driver.navigate().back();
        Thread.sleep(5000);
    //    Util.switchToFirst(driver);

        //System.out.println(urlTasks.toString());
        log.info("线程：{} 用户: {} 需观看 {} 个视频",Thread.currentThread().getName(),userName,urlTasks.size());
        int j = 1;
        for (String urlTask : urlTasks) {
            //兼容服务器停服问题
            if (open) {
                while (LocalDateTime.now().getHour() >= 3 && LocalDateTime.now().getHour() < 5 ) {
                    log.info("当前时间：{} 国开网维护中 程序暂时休眠20min。。。",LocalDateTime.now().toString());
                    TimeUnit.MINUTES.sleep(20);
                }
            }
            // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
            driver.get(urlTask);
            //延长加载时间
            Thread.sleep(3 * 1000);
            Util.switchToUrl(driver,urlTask);
            log.info("线程：{} 用户：{} 当前视频观看进度（{} / {})",Thread.currentThread().getName(),userName,j,urlTasks.size());
            Thread.sleep(2 * 1000);
            driver.executeScript(JS);
            Thread.sleep(2 * 1000);
            List<WebElement> canvas = driver.findElements(By.tagName("canvas"));
            //System.out.println("canvas大小");
            //System.out.println(canvas.size());
            for (WebElement player:canvas) {
                //System.out.println("class是：" + player.getAttribute("class"));
                if (player.getAttribute("class").startsWith("play")) {
                    //System.out.println("找到啦 ");
                    //System.out.println(player);
                    player.click();
                }else {
                    continue;
                }
            }

            Thread.sleep(18000);
            j++;
            /*JavascriptExecutor j =  driver;
            j.executeScript(JS);*/
        }

      try{
          Util.switchToLast(driver);
          driver.get("http://xinjiang.ouchn.cn/course/view.php?id=2660");
          for(WebElement we:driver.findElements(By.cssSelector("h3[div='content']"))){
              System.err.println("??????????"+we.getText());
          }

          for(WebElement we:driver.findElements(By.cssSelector("h3[class='sectionname']"))){
              System.err.println("??????????222"+we.getText());
              if(Strings.isNullOrEmpty(we.getText())){
                  continue;
              }
              if(we.getText().contains("专题五")){
                  we.click();
                  Thread.sleep(2000);
                  driver.get("http://xinjiang.ouchn.cn/mod/url/view.php?id=343895");
                  Thread.sleep(2000);
                  break;
              }
          }
      }catch (Exception e){

      }

        Thread.sleep(5000);
        driver.close();
        driver.quit();
    }

}
